<?php

defined('SYSPATH') or die('Access error!');
/**
 * I18n help 类 
 */
class I18n
{

    public static $lang = 'en-us';
    public static $source = 'en-us';
    protected static $_cache = array();
    public static $current_file = '';

    public static function lang($lang = NULL)
    {
        if ($lang)
        {
            I18n::$lang = strtolower(str_replace(array(' ', '_'), '-', $lang));
        }
        return I18n::$lang;
    }

    public static function get($string, $lang = NULL)
    {
        if (!$lang)
        {
            $lang = I18n::$lang;
        }
        $table = I18n::load($lang);
        return isset($table[$string]) ? $table[$string] : $string;
    }

    public static function load($lang)
    {

        if (isset(I18n::$_cache[$lang]))
        {
            return I18n::$_cache[$lang];
        }
        $table = array();

        $g_parts = explode('-', $lang);

        if (I18n::$current_file != '')
        {
            $lang = $lang . '-' . I18n::$current_file;
        }


        $parts = explode('-', $lang);

        do
        {
            $path = implode(DIRECTORY_SEPARATOR, $parts);

            if ($files = Core::find_file('i18n', $path, NULL, TRUE))
            {
                $t = array();
                foreach ($files as $file)
                {
                    $t = array_merge($t, Core::load($file));
                }
                $table += $t;
            }

            array_pop($parts);
        }
        while ($parts);
        $table = array_merge($table, Arr::flatten(I18n::$_cache));
        return I18n::$_cache[$lang] = $table;
    }

    public static function set_current_file($current_file)
    {
        I18n::$current_file = $current_file;
    }

}
